<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>慢日子 - 记录生活的每一刻</title>
    <!-- 使用国内CDN加速并添加预加载 -->
    <link rel="preconnect" href="https://cdn.bootcdn.net">
    <link rel="preload" href="https://cdn.bootcdn.net/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" as="style">
    <link rel="preload" href="https://cdn.bootcdn.net/ajax/libs/Chart.js/3.9.1/chart.min.js" as="script">
    <link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" crossorigin="anonymous">
    <script src="https://cdn.bootcdn.net/ajax/libs/Chart.js/3.9.1/chart.min.js" crossorigin="anonymous"></script>
    <!-- 内联Tailwind CSS配置和自定义样式，减少HTTP请求 -->
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#6366F1',
                        secondary: '#818CF8',
                        accent: '#A5B4FC',
                        dark: '#1F2937',
                        light: '#F9FAFB',
                        muted: '#6B7280',
                        success: '#10B981',
                        warning: '#F59E0B',
                        danger: '#EF4444',
                        event1: '#8B5CF6',
                        event2: '#EC4899',
                        event3: '#F59E0B',
                        event4: '#10B981',
                        event5: '#3B82F6',
                        event6: '#6366F1',
                        event7: '#06B6D4',
                        event8: '#F43F5E',
                    },
                    fontFamily: {
                        sans: ['system-ui', 'sans-serif'], // 移除Google Fonts依赖，使用系统字体
                        display: ['system-ui', 'sans-serif'] // 移除Google Fonts依赖，使用系统字体
                    },
                    boxShadow: {
                        'soft': '0 4px 20px rgba(0, 0, 0, 0.05)',
                        'medium': '0 8px 30px rgba(0, 0, 0, 0.08)',
                        'hover': '0 12px 40px rgba(0, 0, 0, 0.12)',
                        'inner': 'inset 0 2px 10px rgba(0, 0, 0, 0.05)'
                    },
                    animation: {
                        'fade-in': 'fadeIn 0.5s ease-in-out',
                        'slide-up': 'slideUp 0.4s ease-out',
                        'pulse-soft': 'pulseSoft 2s infinite',
                        'scale': 'scale 0.3s ease-out',
                        'float': 'float 3s ease-in-out infinite',
                        'shimmer': 'shimmer 1.5s infinite linear'
                    },
                    keyframes: {
                        fadeIn: { '0%': { opacity: '0' }, '100%': { opacity: '1' } },
                        slideUp: { '0%': { transform: 'translateY(20px)', opacity: '0' }, '100%': { transform: 'translateY(0)', opacity: '1' } },
                        pulseSoft: { '0%, 100%': { transform: 'scale(1)' }, '50%': { transform: 'scale(1.03)' } },
                        scale: { '0%': { transform: 'scale(0.95)' }, '100%': { transform: 'scale(1)' } },
                        float: { '0%, 100%': { transform: 'translateY(0)' }, '50%': { transform: 'translateY(-10px)' } },
                        shimmer: { '0%': { backgroundPosition: '-1000px 0' }, '100%': { backgroundPosition: '1000px 0' } }
                    }
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto { content-visibility: auto; }
            .text-shadow-sm { text-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); }
            .calendar-day { min-height: 140px; }
            .card-hover { @apply transition-all duration-300 hover:shadow-hover; }
            .bg-gradient-soft { background: linear-gradient(135deg, #f5f7fa 0%, #e4eaf5 100%); }
            .scrollbar-hide::-webkit-scrollbar { display: none; }
            .scrollbar-hide { -ms-overflow-style: none; scrollbar-width: none; }
            .event-tag { @apply text-xs px-1 py-0.5 rounded-full text-white truncate transition-all duration-300 shadow-soft hover:shadow-medium; }
            .btn-primary { @apply bg-primary hover:bg-primary/90 text-white font-medium rounded-xl py-3 px-6 transition-all duration-300 shadow-soft hover:shadow-medium transform hover:-translate-y-0.5; }
            .btn-secondary { @apply bg-white border border-gray-200 hover:border-primary/50 text-dark font-medium rounded-xl py-3 px-6 transition-all duration-300 shadow-soft hover:shadow-medium; }
            .glass { @apply bg-white/70 backdrop-blur-md; }
            .text-gradient { @apply bg-clip-text text-transparent bg-gradient-to-r from-primary to-secondary; }
            .bg-blur { backdrop-filter: blur(8px); }
            .shimmer-effect { @apply bg-[linear-gradient(to_right,#f6f7f8_8%,#edeef1_18%,#f6f7f8_33%)] bg-[length:1000px_104px] animate-shimmer; }
            /* 响应式字体大小 */
            .text-responsive { font-size: clamp(0.75rem, 2vw, 1rem); }
            .text-responsive-event { font-size: clamp(0.5rem, 1.5vw, 0.75rem); }
        }
    </style>
</head>

<body class="bg-light font-sans text-dark min-h-screen flex flex-col">
    <!-- 登录页面 -->
    <div id="loginPage"
        class="min-h-screen flex flex-col items-center justify-center p-6 bg-gradient-to-br from-indigo-50 via-purple-50 to-pink-50 pb-0">
        <!-- 骨架屏加载动画 -->
        <div id="loginSkeleton" class="w-full max-w-md rounded-2xl shadow-medium p-8 relative overflow-hidden hidden">
            <div class="absolute -top-10 -right-10 w-40 h-40 bg-primary/10 rounded-full blur-3xl"></div>
            <div class="absolute -bottom-16 -left-16 w-40 h-40 bg-secondary/10 rounded-full blur-3xl"></div>
            
            <div class="text-center mb-8 relative z-10">
                <div class="w-20 h-20 mx-auto bg-gradient-to-br from-primary to-secondary rounded-full flex items-center justify-center mb-4 shadow-soft shimmer-effect"></div>
                <div class="h-8 bg-gray-200 rounded-xl mb-2 shimmer-effect mx-auto w-3/4"></div>
                <div class="h-4 bg-gray-200 rounded-xl shimmer-effect mx-auto w-1/2"></div>
            </div>
            
            <div class="space-y-4 relative z-10">
                <div>
                    <div class="h-4 bg-gray-200 rounded-xl mb-2 shimmer-effect w-1/3"></div>
                    <div class="h-12 bg-gray-200 rounded-xl shimmer-effect"></div>
                </div>
                
                <div class="h-12 bg-gradient-to-r from-primary/50 to-secondary/50 rounded-xl shimmer-effect"></div>
                
                <div class="text-center">
                    <div class="h-4 bg-gray-200 rounded-xl shimmer-effect mx-auto w-1/2"></div>
                </div>
            </div>
        </div>
        
        <!-- 实际登录表单 (默认隐藏) -->
        <div id="loginForm" class="w-full max-w-md glass rounded-2xl shadow-medium p-8 animate-fade-in relative overflow-hidden hidden">
            <div class="absolute -top-10 -right-10 w-40 h-40 bg-primary/10 rounded-full blur-3xl"></div>
            <div class="absolute -bottom-16 -left-16 w-40 h-40 bg-secondary/10 rounded-full blur-3xl"></div>

            <div class="text-center mb-8 relative z-10">
                <div
                    class="w-20 h-20 mx-auto bg-gradient-to-br from-primary to-secondary rounded-full flex items-center justify-center mb-4 shadow-soft animate-float">
                    <i class="fa fa-calendar-check-o text-3xl text-white"></i>
                </div>
                <h1 class="text-[clamp(1.8rem,5vw,2.5rem)] font-bold text-dark mb-2 font-display text-gradient">慢日子</h1>
                <p class="text-muted">记录生活的每一刻</p>
            </div>

            <div class="space-y-4 relative z-10">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">输入口令登录</label>
                    <div>
                        <input type="text" id="loginPassword"
                            class="w-full px-4 py-3 rounded-xl border border-gray-200 focus:ring-2 focus:ring-primary/30 focus:border-primary transition-all outline-none shadow-sm"
                            placeholder="输入你的专属口令">
                    </div>
                </div>

                <button id="loginBtn"
                    class="w-full bg-gradient-to-r from-primary to-secondary text-white py-3 rounded-xl font-medium shadow-soft hover:shadow-medium flex items-center justify-center transition-all duration-300 transform hover:-translate-y-0.5">
                    <i class="fa fa-sign-in mr-2"></i> 登录
                </button>

                <div class="text-center text-sm text-muted">
                    <p>参考口令: <span class="font-medium text-primary">我是紫紫大王</span></p>
                </div>
            </div>
        </div>

        <div class="mt-8 text-center text-muted text-sm">
            <p>慢日子 &copy; 2025 | 记录生活，不虚度时光</p>
        </div>
    </div>

    <!-- 主页面 -->
    <div id="mainPage" class="hidden flex flex-col min-h-screen">
        <!-- 顶部导航 -->
        <header class="glass shadow-sm sticky top-0 z-30 transition-all duration-300">
            <div class="container mx-auto px-4 py-3 flex justify-between items-center">
                <div class="flex items-center">
                    <h1 class="text-xl font-bold font-display text-gradient">慢日子</h1>
                </div>
                <div class="flex items-center space-x-3">
                    <button id="statsBtn"
                        class="text-muted hover:text-primary transition-colors p-2 rounded-full hover:bg-primary/10 relative z-10">
                        <i class="fa fa-bar-chart"></i>
                        <span class="absolute top-0 right-0 w-2 h-2 bg-primary rounded-full"></span>
                    </button>
                </div>
            </div>
        </header>

        <!-- 日历标题栏 -->
        <div class="glass py-4 px-4 shadow-sm">
            <div class="container mx-auto flex justify-between items-center">
                <button id="prevMonth" class="p-2 rounded-full hover:bg-gray-100 transition-colors">
                    <i class="fa fa-chevron-left text-muted"></i>
                </button>
                <h2 id="currentMonth" class="text-xl font-medium">2025年8月</h2>
                <button id="nextMonth" class="p-2 rounded-full hover:bg-gray-100 transition-colors">
                    <i class="fa fa-chevron-right text-muted"></i>
                </button>
            </div>
        </div>

        <!-- 日历主体 -->
        <main class="flex-1 p-4">
            <div class="container mx-auto">
                <!-- 星期标题 -->
                <div class="grid grid-cols-7 mb-2">
                    <div class="text-center text-xs text-muted font-medium py-2">日</div>
                    <div class="text-center text-xs text-muted font-medium py-2">一</div>
                    <div class="text-center text-xs text-muted font-medium py-2">二</div>
                    <div class="text-center text-xs text-muted font-medium py-2">三</div>
                    <div class="text-center text-xs text-muted font-medium py-2">四</div>
                    <div class="text-center text-xs text-muted font-medium py-2">五</div>
                    <div class="text-center text-xs text-muted font-medium py-2">六</div>
                </div>

                <!-- 日历网格 -->
                <div id="calendarGrid" class="grid grid-cols-7 gap-2">
                    <!-- 日历天数将通过JS动态生成 -->
                </div>

                <!-- 今日记录预览 -->
                <div id="todayPreview" class="mt-6 glass rounded-2xl shadow-soft p-5 animate-slide-up border border-gray-100/50">
                    <div class="flex justify-between items-center mb-4">
                        <h3 class="text-lg font-bold text-dark flex items-center">
                            <i class="fa fa-calendar-check-o text-primary mr-2"></i>今日记录
                        </h3>
                        <span id="todayDate" class="text-sm font-medium text-primary bg-primary/10 px-3 py-1 rounded-full"></span>
                    </div>
                    <div id="todayEvents" class="flex flex-wrap gap-2 min-h-[50px]">
                        <div class="text-muted text-base italic flex items-center">
                            <i class="fa fa-info-circle mr-2"></i>点击日期添加记录
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div> <!-- 记录页面 -->
    <div id="recordPage" class="hidden flex flex-col min-h-screen">
        <!-- 顶部导航 -->
        <header class="glass shadow-sm sticky top-0 z-30">
            <div class="container mx-auto px-4 py-3 flex justify-between items-center">
                <button id="backToCalendar"
                    class="text-muted hover:text-primary transition-colors p-2 rounded-full hover:bg-primary/10">
                    <i class="fa fa-arrow-left"></i>
                </button>
                <h1 class="text-xl font-bold font-display" id="recordDateTitle">2025年08月07日</h1>
                <div class="w-8"></div>
            </div>
        </header>
        <main class="flex-1 p-4">
            <div class="container mx-auto">
                <div class="glass rounded-xl shadow-soft p-5 mb-6 animate-slide-up">
                    <h2 class="text-lg font-medium mb-3 flex items-center">
                        <i class="fa fa-list-ul text-primary mr-2"></i>今日事件
                    </h2>
                    <div id="selectedEvents" class="flex flex-wrap gap-2 min-h-[40px] mb-3">
                        <!-- 已选择的事件将显示在这里 -->
                    </div>
                    <p class="text-sm text-muted flex items-center">
                        <i class="fa fa-lightbulb-o mr-1"></i> 点击下方常用事件添加到今日记录
                    </p>
                </div>
                <div class="glass rounded-xl shadow-soft p-5 animate-slide-up" style="animation-delay: 0.1s">
                    <h2 class="text-lg font-medium mb-4 flex items-center">
                        <i class="fa fa-star text-primary mr-2"></i>常用事件
                    </h2>
                    <div id="commonEvents" class="grid grid-cols-3 gap-3">
                        <!-- 常用事件将通过JS动态生成 -->
                    </div>

                    <div class="mt-6 pt-4 border-t border-gray-100">
                        <button id="addNewEventBtn"
                            class="w-full py-3 border-2 border-dashed border-gray-200 rounded-xl text-muted hover:border-primary hover:text-primary transition-colors flex items-center justify-center group">
                            <i class="fa fa-plus-circle mr-2 transform group-hover:scale-110 transition-transform"></i>
                            添加新事件
                        </button>
                    </div>
                </div>
            </div>
        </main>

        <!-- 底部保存按钮 -->
        <div class="sticky bottom-0 glass border-t border-gray-100 py-3 shadow-[0_-2px_10px_rgba(0,0,0,0.03)] z-20">
            <div class="container mx-auto px-4">
                <button id="saveRecordBtn"
                    class="w-full bg-gradient-to-r from-primary to-secondary text-white py-3 rounded-xl font-medium shadow-soft hover:shadow-medium transition-all duration-300 transform hover:-translate-y-0.5">
                    保存记录
                </button>
            </div>
        </div>
    </div>

    <!-- 添加新事件弹窗 -->
    <div id="newEventModal" class="fixed inset-0 bg-black/40 z-50 hidden items-center justify-center backdrop-blur-sm">
        <div class="glass rounded-2xl shadow-medium w-full max-w-md mx-4 p-6 transform transition-all animate-scale">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-xl font-bold font-display">添加新事件</h3>
                <button id="closeNewEventModal"
                    class="text-muted hover:text-primary transition-colors p-1 rounded-full hover:bg-gray-100">
                    <i class="fa fa-times text-xl"></i>
                </button>
            </div>

            <div class="space-y-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">事件名称</label>
                    <input type="text" id="newEventName"
                        class="w-full px-4 py-3 rounded-xl border border-gray-200 focus:ring-2 focus:ring-primary/30 focus:border-primary transition-all outline-none shadow-sm"
                        placeholder="输入事件名称">
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">选择颜色</label>
                    <div class="flex gap-2 flex-wrap">
                        <button
                            class="event-color-btn w-6 h-6 rounded-full bg-event1 border-2 border-white shadow-sm active"
                            data-color="#8B5CF6"></button>
                        <button
                            class="event-color-btn w-6 h-6 rounded-full bg-event2 border-2 border-transparent shadow-sm"
                            data-color="#EC4899"></button>
                        <button
                            class="event-color-btn w-6 h-6 rounded-full bg-event3 border-2 border-transparent shadow-sm"
                            data-color="#F59E0B"></button>
                        <button
                            class="event-color-btn w-6 h-6 rounded-full bg-event4 border-2 border-transparent shadow-sm"
                            data-color="#10B981"></button>
                        <button
                            class="event-color-btn w-6 h-6 rounded-full bg-event5 border-2 border-transparent shadow-sm"
                            data-color="#3B82F6"></button>
                        <button
                            class="event-color-btn w-6 h-6 rounded-full bg-event6 border-2 border-transparent shadow-sm"
                            data-color="#6366F1"></button>
                        <button
                            class="event-color-btn w-6 h-6 rounded-full bg-event7 border-2 border-transparent shadow-sm"
                            data-color="#06B6D4"></button>
                        <button
                            class="event-color-btn w-6 h-6 rounded-full bg-event8 border-2 border-transparent shadow-sm"
                            data-color="#F43F5E"></button>
                        <button id="moreColorsBtn" class="w-6 h-6 rounded-full border-2 border-gray-300 shadow-sm flex items-center justify-center text-gray-500 hover:border-primary hover:text-primary transition-colors">
                            <i class="fa fa-plus text-xs"></i>
                        </button>
                    </div>
                    <!-- 更多颜色选择器 (默认隐藏) -->
                    <div id="moreColorsContainer" class="hidden mt-3">
                        <div class="flex gap-2 flex-wrap">
                            <button
                                class="event-color-btn w-6 h-6 rounded-full border-2 border-transparent shadow-sm"
                                data-color="#EF4444" style="background-color: #EF4444;"></button>
                            <button
                                class="event-color-btn w-6 h-6 rounded-full border-2 border-transparent shadow-sm"
                                data-color="#F97316" style="background-color: #F97316;"></button>
                            <button
                                class="event-color-btn w-6 h-6 rounded-full border-2 border-transparent shadow-sm"
                                data-color="#EAB308" style="background-color: #EAB308;"></button>
                            <button
                                class="event-color-btn w-6 h-6 rounded-full border-2 border-transparent shadow-sm"
                                data-color="#84CC16" style="background-color: #84CC16;"></button>
                            <button
                                class="event-color-btn w-6 h-6 rounded-full border-2 border-transparent shadow-sm"
                                data-color="#22C55E" style="background-color: #22C55E;"></button>
                            <button
                                class="event-color-btn w-6 h-6 rounded-full border-2 border-transparent shadow-sm"
                                data-color="#14B8A6" style="background-color: #14B8A6;"></button>
                            <button
                                class="event-color-btn w-6 h-6 rounded-full border-2 border-transparent shadow-sm"
                                data-color="#0EA5E9" style="background-color: #0EA5E9;"></button>
                            <button
                                class="event-color-btn w-6 h-6 rounded-full border-2 border-transparent shadow-sm"
                                data-color="#A855F7" style="background-color: #A855F7;"></button>
                            <button
                                class="event-color-btn w-6 h-6 rounded-full border-2 border-transparent shadow-sm"
                                data-color="#D946EF" style="background-color: #D946EF;"></button>
                            <button
                                class="event-color-btn w-6 h-6 rounded-full border-2 border-transparent shadow-sm"
                                data-color="#64748B" style="background-color: #64748B;"></button>
                            <button
                                class="event-color-btn w-6 h-6 rounded-full border-2 border-transparent shadow-sm"
                                data-color="#94A3B8" style="background-color: #94A3B8;"></button>
                        </div>
                    </div>
                </div>

                <div class="pt-2">
                    <button id="confirmNewEventBtn"
                        class="w-full bg-gradient-to-r from-primary to-secondary text-white py-3 rounded-xl font-medium shadow-soft hover:shadow-medium transition-all duration-300">
                        保存事件
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 日历事件详情弹窗 -->
    <div id="dayEventsModal" class="fixed inset-0 bg-black/40 z-50 hidden items-center justify-center backdrop-blur-sm">
        <div
            class="glass rounded-2xl shadow-medium w-full max-w-md mx-4 p-6 transform transition-all animate-scale max-h-[80vh] flex flex-col">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-xl font-bold font-display" id="dayEventsTitle">2025年8月15日 事件</h3>
                <button id="closeDayEventsModal"
                    class="text-muted hover:text-primary transition-colors p-1 rounded-full hover:bg-gray-100">
                    <i class="fa fa-times text-xl"></i>
                </button>
            </div>

            <div id="dayEventsContent" class="flex-1 overflow-y-auto scrollbar-hide pb-4">
                <!-- 事件内容将通过JS动态生成 -->
                <div class="text-center text-muted py-8">
                    <i class="fa fa-calendar-o text-4xl mb-2 opacity-30"></i>
                    <p>这一天没有记录事件</p>
                </div>
            </div>

            <div class="pt-4 border-t border-gray-100">
                <button id="gotoRecordBtn"
                    class="w-full bg-gradient-to-r from-primary to-secondary text-white py-3 rounded-xl font-medium shadow-soft hover:shadow-medium transition-all duration-300">
                    <i class="fa fa-pencil mr-2"></i>编辑今日记录
                </button>
            </div>
        </div>
    </div>

    <!-- 事件备注弹窗 -->
    <div id="eventNoteModal" class="fixed inset-0 bg-black/40 z-50 hidden items-center justify-center backdrop-blur-sm">
        <div class="glass rounded-2xl shadow-medium w-full max-w-md mx-4 p-6 transform transition-all animate-scale">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-xl font-bold font-display" id="eventNoteTitle">添加备注</h3>
                <button id="closeEventNoteModal"
                    class="text-muted hover:text-primary transition-colors p-1 rounded-full hover:bg-gray-100">
                    <i class="fa fa-times text-xl"></i>
                </button>
            </div>

            <div class="space-y-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">备注内容</label>
                    <textarea id="eventNoteContent" rows="4"
                        class="w-full px-4 py-3 rounded-xl border border-gray-200 focus:ring-2 focus:ring-primary/30 focus:border-primary transition-all outline-none shadow-sm"
                        placeholder="记录一些想法和感受..."></textarea>
                </div>

                <div class="pt-2 flex gap-3">
                    <button id="cancelEventNoteBtn"
                        class="flex-1 py-3 border border-gray-200 rounded-xl text-muted hover:border-gray-300 transition-colors">
                        取消
                    </button>
                    <button id="saveEventNoteBtn"
                        class="flex-1 bg-gradient-to-r from-primary to-secondary text-white py-3 rounded-xl font-medium shadow-soft hover:shadow-medium transition-all duration-300">
                        保存备注
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 统计页面 -->
    <div id="statsPage" class="hidden flex flex-col min-h-screen">
        <!-- 顶部导航 -->
        <header class="glass shadow-sm sticky top-0 z-30">
            <div class="container mx-auto px-4 py-3 flex justify-between items-center">
                <button id="backToMainFromStats"
                    class="text-muted hover:text-primary transition-colors p-2 rounded-full hover:bg-primary/10">
                    <i class="fa fa-arrow-left"></i>
                </button>
                <h1 class="text-xl font-bold font-display text-gradient">数据统计</h1>
                <div class="w-8"></div>
            </div>
        </header>

        <main class="flex-1 p-4">
            <div class="container mx-auto">
                <div class="glass rounded-xl shadow-soft p-5 mb-6 animate-slide-up">
                    <h2 class="text-lg font-medium mb-4 flex items-center">
                        <i class="fa fa-line-chart text-primary mr-2"></i>月度概览
                    </h2>
                    <div class="h-64">
                        <canvas id="monthlyChart"></canvas>
                    </div>
                </div>

                <div class="glass rounded-xl shadow-soft p-5 mb-6 animate-slide-up" style="animation-delay: 0.1s">
                    <h2 class="text-lg font-medium mb-4 flex items-center">
                        <i class="fa fa-pie-chart text-primary mr-2"></i>事件分布
                    </h2>
                    <div class="h-64">
                        <canvas id="eventsChart"></canvas>
                    </div>
                </div>

                <div class="glass rounded-xl shadow-soft p-5 animate-slide-up" style="animation-delay: 0.2s">
                    <h2 class="text-lg font-medium mb-4 flex items-center">
                        <i class="fa fa-trophy text-primary mr-2"></i>最近30天总结
                    </h2>
                    <div class="space-y-4">
                        <div class="flex justify-between items-center p-3 bg-white/50 rounded-lg">
                            <span class="text-muted flex items-center">
                                <i class="fa fa-calendar-check-o mr-2"></i>总记录天数
                            </span>
                            <span id="totalDays" class="font-medium text-lg">24天</span>
                        </div>
                        <div class="flex justify-between items-center p-3 bg-white/50 rounded-lg">
                            <span class="text-muted flex items-center">
                                <i class="fa fa-list-alt mr-2"></i>总事件数
                            </span>
                            <span id="totalEvents" class="font-medium text-lg">48件</span>
                        </div>
                        <div class="flex justify-between items-center p-3 bg-white/50 rounded-lg">
                            <span class="text-muted flex items-center">
                                <i class="fa fa-fire mr-2"></i>最常做的事
                            </span>
                            <span id="mostFrequentEvent" class="font-medium text-lg text-primary">阅读</span>
                        </div>
                    </div>

                    <div class="mt-6 pt-4 border-t border-gray-100">
                        <p class="text-center text-muted italic">
                            "日子虽然过得快，但你做了很多事，<br>我们都在慢慢过日子，没有虚度。"
                        </p>
                    </div>
                </div>
            </div>
        </main>
    </div>

    <!-- 我的页面 -->
    <div id="profilePage" class="hidden flex flex-col min-h-screen">
        <!-- 顶部导航 -->
        <header class="glass shadow-sm sticky top-0 z-30">
            <div class="container mx-auto px-4 py-3 flex justify-between items-center">
                <button id="backToMainFromProfile"
                    class="text-muted hover:text-primary transition-colors p-2 rounded-full hover:bg-primary/10">
                    <i class="fa fa-arrow-left"></i>
                </button>
                <h1 class="text-xl font-bold font-display text-gradient">我的</h1>
                <div class="w-8"></div>
            </div>
        </header>

        <main class="flex-1 p-4">
            <div class="container mx-auto">
                <div
                    class="bg-gradient-to-br from-primary to-secondary rounded-2xl shadow-soft p-6 text-white mb-6 relative overflow-hidden animate-slide-up">
                    <div class="absolute top-0 right-0 w-32 h-32 bg-white/10 rounded-full blur-3xl"></div>
                    <div class="absolute bottom-0 left-0 w-24 h-24 bg-white/10 rounded-full blur-3xl"></div>

                    <div class="flex items-center relative z-10">
                        <div
                            class="w-16 h-16 rounded-full bg-white/20 backdrop-blur-sm flex items-center justify-center mr-4 border border-white/30">
                            <i class="fa fa-user text-2xl"></i>
                        </div>
                        <div>
                            <h2 class="text-xl font-bold" id="userName">紫紫大王</h2>
                            <p class="text-white/80 text-sm">记录生活，享受慢时光</p>
                        </div>
                    </div>

                    <div class="grid grid-cols-3 gap-2 mt-6 text-center relative z-10">
                        <div class="bg-white/20 backdrop-blur-sm rounded-xl p-3">
                            <div class="text-2xl font-bold" id="profileTotalDays">24</div>
                            <div class="text-xs text-white/80">记录天数</div>
                        </div>
                        <div class="bg-white/20 backdrop-blur-sm rounded-xl p-3">
                            <div class="text-2xl font-bold" id="profileTotalEvents">48</div>
                            <div class="text-xs text-white/80">事件总数</div>
                        </div>
                        <div class="bg-white/20 backdrop-blur-sm rounded-xl p-3">
                            <div class="text-2xl font-bold" id="profileEventTypes">8</div>
                            <div class="text-xs text-white/80">事件类型</div>
                        </div>
                    </div>
                </div>

                <div class="glass rounded-xl shadow-soft p-5 mb-6 animate-slide-up" style="animation-delay: 0.1s">
                    <h3 class="text-lg font-medium mb-4 flex items-center">
                        <i class="fa fa-tags text-primary mr-2"></i>事件统计
                    </h3>
                    <div id="allEventsList" class="space-y-3 max-h-64 overflow-y-auto pr-1 scrollbar-hide">
                        <!-- 所有事件将通过JS动态生成 -->
                    </div>
                </div>

                <div class="glass rounded-xl shadow-soft p-5 animate-slide-up" style="animation-delay: 0.2s">
                    <button id="logoutBtn"
                        class="w-full py-3 border border-gray-200 rounded-xl text-muted hover:border-red-400 hover:text-red-500 transition-colors flex items-center justify-center group">
                        <i
                            class="fa fa-sign-out mr-2 transform group-hover:translate-x-[-2px] transition-transform"></i>
                        退出登录
                    </button>
                </div>
            </div>
        </main>
    </div>

    <!-- 公共底部导航栏 -->
    <footer class="glass border-t border-gray-100 py-3 sticky bottom-0 z-20 shadow-[0_-2px_10px_rgba(0,0,0,0.03)]">
        <div class="container mx-auto px-4">
            <div class="flex justify-around">
                <button id="calendarNavBtn" class="flex flex-col items-center text-muted hover:text-primary transition-colors">
                    <i class="fa fa-calendar text-lg"></i>
                    <span class="text-xs mt-1">日历</span>
                </button>
                <button id="addEventBtn"
                    class="w-14 h-14 bg-gradient-to-br from-primary to-secondary rounded-full -mt-8 flex items-center justify-center text-white shadow-medium hover:shadow-hover transition-all duration-300 animate-pulse-soft">
                    <i class="fa fa-plus text-xl"></i>
                </button>
                <button id="profileNavBtn" class="flex flex-col items-center text-muted hover:text-primary transition-colors">
                    <i class="fa fa-user-o text-lg"></i>
                    <span class="text-xs mt-1">我的</span>
                </button>
            </div>
        </div>
    </footer>

    <script>
        // 全局数据存储
        const appData = {
            currentUser: null,
            fileSystem: {
                users: {}, // 用户信息
                events: {}, // 事件定义
                records: {} // 记录数据
            },
            currentDate: new Date(),
            selectedDate: null,
            selectedEvents: [],
            editingEvent: null, // 当前正在编辑备注的事件
            commonColors: [
                '#8B5CF6', '#EC4899', '#F59E0B', '#10B981',
                '#3B82F6', '#6366F1', '#06B6D4', '#F43F5E'
            ]
        };

        // API 基础URL
        const API_BASE_URL = '/api';

        // 从服务器加载用户数据
        const loadUserDataFromServer = async () => {
            if (!appData.currentUser) return;
            
            try {
                const response = await fetch(`${API_BASE_URL}/user/${encodeURIComponent(appData.currentUser)}`);
                if (response.ok) {
                    const userData = await response.json();
                    console.log('从服务器获取的用户数据:', userData); // 调试信息
                    appData.fileSystem.users[appData.currentUser] = userData.info || {};
                    appData.fileSystem.events[appData.currentUser] = userData.events || {};
                    appData.fileSystem.records[appData.currentUser] = userData.records || {};
                    console.log('更新后的文件系统数据:', appData.fileSystem); // 调试信息
                } else {
                    console.error('从服务器加载用户数据失败:', response.status);
                }
            } catch (error) {
                console.error('从服务器加载用户数据时出错:', error);
            }
        };

        // 保存用户数据到服务器
        const saveUserDataToServer = async () => {
            if (!appData.currentUser) return false;
            
            try {
                const userData = {
                    info: appData.fileSystem.users[appData.currentUser] || {},
                    events: appData.fileSystem.events[appData.currentUser] || {},
                    records: appData.fileSystem.records[appData.currentUser] || {}
                };
                
                const response = await fetch(`${API_BASE_URL}/user/${encodeURIComponent(appData.currentUser)}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(userData)
                });
                
                if (response.ok) {
                    const result = await response.json();
                    return result.success;
                } else {
                    console.error('保存用户数据到服务器失败:', response.status);
                    return false;
                }
            } catch (error) {
                console.error('保存用户数据到服务器时出错:', error);
                return false;
            }
        };

        // 初始化时从服务器加载数据
        const loadFileSystem = () => {
            const savedFileSystem = localStorage.getItem('slowDayFileSystem');
            if (savedFileSystem) {
                // 如果存在旧的存储格式，迁移数据
                const oldData = JSON.parse(savedFileSystem);
                appData.fileSystem = oldData;
                // 清除旧的存储格式
                localStorage.removeItem('slowDayFileSystem');
                // 保存为新的用户独立存储格式
                saveFileSystem();
            } else {
                // 尝试从服务器加载数据
                loadUserData();
            }
        };

        // 数据迁移函数 - 修复历史统计错误（已移至后端处理）
        const migrateEventData = async () => {
            console.log('数据迁移功能已移至后端处理，请直接在数据库层面执行修复脚本');
            return true;
        };

        // 为每个用户保存独立的JSON数据
        const saveUserData = () => {
            if (!appData.currentUser) return false;
            
            try {
                const userData = {
                    info: appData.fileSystem.users[appData.currentUser] || {},
                    events: appData.fileSystem.events[appData.currentUser] || {},
                    records: appData.fileSystem.records[appData.currentUser] || {}
                };
                
                localStorage.setItem(`slowDayUser_${appData.currentUser}`, JSON.stringify(userData));
                return true;
            } catch (e) {
                console.error('保存用户数据失败:', e);
                return false;
            }
        };

        // 从独立的用户存储中加载数据
        const loadUserData = () => {
            if (!appData.currentUser) return;
            
            try {
                const userDataStr = localStorage.getItem(`slowDayUser_${appData.currentUser}`);
                if (userDataStr) {
                    const userData = JSON.parse(userDataStr);
                    appData.fileSystem.users[appData.currentUser] = userData.info || {};
                    appData.fileSystem.events[appData.currentUser] = userData.events || {};
                    appData.fileSystem.records[appData.currentUser] = userData.records || {};
                }
            } catch (e) {
                console.error('加载用户数据失败:', e);
            }
        };

        // DOM元素
        const elements = {
            loginPage: document.getElementById('loginPage'),
            mainPage: document.getElementById('mainPage'),
            recordPage: document.getElementById('recordPage'),
            statsPage: document.getElementById('statsPage'),
            profilePage: document.getElementById('profilePage'),
            newEventModal: document.getElementById('newEventModal'),
            dayEventsModal: document.getElementById('dayEventsModal'),
            eventNoteModal: document.getElementById('eventNoteModal'),
            // 底部导航栏
            bottomNav: document.querySelector('footer'),
            calendarNavBtn: document.getElementById('calendarNavBtn'),
            addEventBtn: document.getElementById('addEventBtn'),
            profileNavBtn: document.getElementById('profileNavBtn'),

            // 登录页面
            loginPassword: document.getElementById('loginPassword'),
            loginBtn: document.getElementById('loginBtn'),

            // 主页面
            prevMonth: document.getElementById('prevMonth'),
            nextMonth: document.getElementById('nextMonth'),
            currentMonth: document.getElementById('currentMonth'),
            calendarGrid: document.getElementById('calendarGrid'),
            todayEvents: document.getElementById('todayEvents'),
            todayDate: document.getElementById('todayDate'),
            addEventBtn: document.getElementById('addEventBtn'),
            statsBtn: document.getElementById('statsBtn'),
            profileNavBtn: document.getElementById('profileNavBtn'),
            calendarNavBtn: document.getElementById('calendarNavBtn'),

            // 记录页面
            backToCalendar: document.getElementById('backToCalendar'),
            recordDateTitle: document.getElementById('recordDateTitle'),
            selectedEvents: document.getElementById('selectedEvents'),
            commonEvents: document.getElementById('commonEvents'),
            addNewEventBtn: document.getElementById('addNewEventBtn'),
            saveRecordBtn: document.getElementById('saveRecordBtn'),

            // 新增事件弹窗
            closeNewEventModal: document.getElementById('closeNewEventModal'),
            newEventName: document.getElementById('newEventName'),
            confirmNewEventBtn: document.getElementById('confirmNewEventBtn'),

            // 日历事件详情弹窗
            closeDayEventsModal: document.getElementById('closeDayEventsModal'),
            dayEventsTitle: document.getElementById('dayEventsTitle'),
            dayEventsContent: document.getElementById('dayEventsContent'),
            gotoRecordBtn: document.getElementById('gotoRecordBtn'),

            // 事件备注弹窗
            closeEventNoteModal: document.getElementById('closeEventNoteModal'),
            eventNoteTitle: document.getElementById('eventNoteTitle'),
            eventNoteContent: document.getElementById('eventNoteContent'),
            cancelEventNoteBtn: document.getElementById('cancelEventNoteBtn'),
            saveEventNoteBtn: document.getElementById('saveEventNoteBtn'),

            // 统计页面
            backToMainFromStats: document.getElementById('backToMainFromStats'),

            // 统计数据
            totalDays: document.getElementById('totalDays'),
            totalEvents: document.getElementById('totalEvents'),
            mostFrequentEvent: document.getElementById('mostFrequentEvent'),

            // 我的页面
            backToMainFromProfile: document.getElementById('backToMainFromProfile'),
            userName: document.getElementById('userName'),
            allEventsList: document.getElementById('allEventsList'),
            logoutBtn: document.getElementById('logoutBtn'),
            profileTotalDays: document.getElementById('profileTotalDays'),
            profileTotalEvents: document.getElementById('profileTotalEvents'),
            profileEventTypes: document.getElementById('profileEventTypes')
        };

        // 工具函数
        const utils = {
            // 文件系统风格存储 - 保存数据到服务器
            saveFileSystem: () => {
                try {
                    // 保存当前用户的数据到服务器
                    if (appData.currentUser) {
                        return saveUserDataToServer();
                    }
                    return true;
                } catch (e) {
                    console.error('保存文件系统失败:', e);
                    return false;
                }
            },

            // 获取用户数据
            getUserData: (username) => {
                // 如果请求的用户不是当前用户，需要从存储中加载该用户的数据
                if (username !== appData.currentUser) {
                    try {
                        const userDataStr = localStorage.getItem(`slowDayUser_${username}`);
                        if (userDataStr) {
                            const userData = JSON.parse(userDataStr);
                            return {
                                info: userData.info || {},
                                events: userData.events || {},
                                records: userData.records || {}
                            };
                        }
                    } catch (e) {
                        console.error('加载用户数据失败:', e);
                    }
                }
                
                // 如果是当前用户或加载失败，返回当前内存中的数据
                return {
                    info: appData.fileSystem.users[username] || {},
                    events: appData.fileSystem.events[username] || {},
                    records: appData.fileSystem.records[username] || {}
                };
            },

            // 日期格式化
            formatDate: (date, format = 'YYYY-MM-DD') => {
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');

                return format
                    .replace('YYYY', year)
                    .replace('MM', month)
                    .replace('DD', day)
                    .replace('M', date.getMonth() + 1)
                    .replace('D', date.getDate());
            },

            // 获取月份的天数
            getDaysInMonth: (year, month) => {
                return new Date(year, month + 1, 0).getDate();
            },

            // 获取月份第一天是星期几
            getFirstDayOfMonth: (year, month) => {
                return new Date(year, month, 1).getDay();
            },

            // 显示通知
            showToast: (message, type = 'success') => {
                // 检查是否已有toast
                const existingToast = document.querySelector('.toast-notification');
                if (existingToast) {
                    existingToast.remove();
                }

                const toast = document.createElement('div');
                toast.className = `fixed bottom-20 left-1/2 transform -translate-x-1/2 px-4 py-3 rounded-xl shadow-medium z-50 flex items-center toast-notification animate-fade-in ${type === 'success' ? 'bg-success text-white' : 'bg-danger text-white'
                    }`;
                toast.innerHTML = `
                    <i class="fa fa-${type === 'success' ? 'check-circle' : 'exclamation-circle'} mr-2"></i>
                    ${message}
                `;
                document.body.appendChild(toast);

                setTimeout(() => {
                    toast.classList.add('opacity-0', 'transition-opacity', 'duration-300');
                    setTimeout(() => toast.remove(), 300);
                }, 2000);
            }
        };

        // 页面控制器
        const pageController = {
            // 更新底部导航栏激活状态
            updateBottomNavActiveState: (activePage) => {
                // 重置所有按钮状态
                elements.calendarNavBtn.classList.remove('text-primary');
                elements.calendarNavBtn.classList.add('text-muted', 'hover:text-primary');
                elements.profileNavBtn.classList.remove('text-primary');
                elements.profileNavBtn.classList.add('text-muted', 'hover:text-primary');
                
                // 根据当前页面设置激活状态
                switch (activePage) {
                    case 'main':
                    case 'record':
                    case 'stats':
                        elements.calendarNavBtn.classList.remove('text-muted', 'hover:text-primary');
                        elements.calendarNavBtn.classList.add('text-primary');
                        break;
                    case 'profile':
                        elements.profileNavBtn.classList.remove('text-muted', 'hover:text-primary');
                        elements.profileNavBtn.classList.add('text-primary');
                        break;
                }
            },
            
            // 重新绑定底部导航栏按钮事件监听器
            bindBottomNavEvents: () => {
                // 移除所有现有的点击事件监听器
                const newCalendarBtn = elements.calendarNavBtn.cloneNode(true);
                elements.calendarNavBtn.parentNode.replaceChild(newCalendarBtn, elements.calendarNavBtn);
                elements.calendarNavBtn = newCalendarBtn;
                
                const newProfileBtn = elements.profileNavBtn.cloneNode(true);
                elements.profileNavBtn.parentNode.replaceChild(newProfileBtn, elements.profileNavBtn);
                elements.profileNavBtn = newProfileBtn;
                
                // 添加新的事件监听器
                elements.calendarNavBtn.addEventListener('click', pageController.showMainPage);
                elements.profileNavBtn.addEventListener('click', pageController.showProfilePage);
            },
            // 显示登录页面
            showLoginPage: () => {
                // 显示登录页面
                elements.loginPage.classList.remove('hidden');
                
                // 隐藏底部导航栏
                elements.bottomNav.classList.add('hidden');
                
                // 显示骨架屏
                document.getElementById('loginSkeleton').classList.remove('hidden');
                document.getElementById('loginForm').classList.add('hidden');
                
                // 隐藏其他页面
                elements.mainPage.classList.add('hidden');
                elements.recordPage.classList.add('hidden');
                elements.statsPage.classList.add('hidden');
                elements.profilePage.classList.add('hidden');
                elements.newEventModal.classList.add('hidden');
                elements.newEventModal.classList.remove('flex');
                elements.dayEventsModal.classList.add('hidden');
                elements.dayEventsModal.classList.remove('flex');
                elements.eventNoteModal.classList.add('hidden');
                elements.eventNoteModal.classList.remove('flex');
                
                // 延迟显示实际表单，模拟加载效果
                setTimeout(() => {
                    document.getElementById('loginSkeleton').classList.add('hidden');
                    document.getElementById('loginForm').classList.remove('hidden');
                }, 500);
            },

            // 显示主页面
            showMainPage: () => {
                elements.loginPage.classList.add('hidden');
                elements.mainPage.classList.remove('hidden');
                elements.recordPage.classList.add('hidden');
                elements.statsPage.classList.add('hidden');
                elements.profilePage.classList.add('hidden');
                elements.newEventModal.classList.add('hidden');
                elements.newEventModal.classList.remove('flex');
                elements.dayEventsModal.classList.add('hidden');
                elements.dayEventsModal.classList.remove('flex');
                elements.eventNoteModal.classList.add('hidden');
                elements.eventNoteModal.classList.remove('flex');
                
                // 显示底部导航栏
                elements.bottomNav.classList.remove('hidden');

                elements.todayDate.textContent = utils.formatDate(new Date(), 'YYYY年MM月DD日');
                calendarController.renderCalendar();
                calendarController.updateTodayEvents();
                
                // 更新底部导航栏激活状态
                pageController.updateBottomNavActiveState('main');
                // 重新绑定底部导航栏事件监听器
                pageController.bindBottomNavEvents();
            },

            // 显示记录页面
            showRecordPage: (date) => {
                appData.selectedDate = date || new Date();
                const dateStr = utils.formatDate(appData.selectedDate);
                const userRecords = appData.fileSystem.records[appData.currentUser] || {};

                // 从记录中获取事件列表，如果有备注则只取事件名称
                appData.selectedEvents = userRecords[dateStr] ?
                    userRecords[dateStr].map(item => item.event) : [];

                elements.recordDateTitle.textContent = utils.formatDate(appData.selectedDate, 'YYYY年MM月DD日');
                recordController.renderSelectedEvents();
                recordController.renderCommonEvents();

                elements.loginPage.classList.add('hidden');
                elements.mainPage.classList.add('hidden');
                elements.recordPage.classList.remove('hidden');
                elements.statsPage.classList.add('hidden');
                elements.profilePage.classList.add('hidden');
                elements.newEventModal.classList.add('hidden');
                elements.newEventModal.classList.remove('flex');
                elements.dayEventsModal.classList.add('hidden');
                elements.dayEventsModal.classList.remove('flex');
                elements.eventNoteModal.classList.add('hidden');
                elements.eventNoteModal.classList.remove('flex');
                
                // 显示底部导航栏
                elements.bottomNav.classList.remove('hidden');
            },

            // 显示统计页面
            showStatsPage: () => {
                try {
                    // 先显示页面再渲染图表，确保DOM已加载
                    elements.loginPage.classList.add('hidden');
                    elements.mainPage.classList.add('hidden');
                    elements.recordPage.classList.add('hidden');
                    elements.statsPage.classList.remove('hidden');
                    elements.profilePage.classList.add('hidden');
                    elements.newEventModal.classList.add('hidden');
                    elements.newEventModal.classList.remove('flex');
                    elements.dayEventsModal.classList.add('hidden');
                    elements.dayEventsModal.classList.remove('flex');
                    elements.eventNoteModal.classList.add('hidden');
                    elements.eventNoteModal.classList.remove('flex');
                    
                    // 显示底部导航栏
                    elements.bottomNav.classList.remove('hidden');

                    // 延迟渲染图表，确保页面已显示
                    setTimeout(() => {
                        statsController.renderStats();
                    }, 100);
                    
                    // 更新底部导航栏激活状态
                    pageController.updateBottomNavActiveState('stats');
                    // 重新绑定底部导航栏事件监听器
                    pageController.bindBottomNavEvents();
                } catch (error) {
                    console.error('显示统计页面失败:', error);
                    utils.showToast('加载统计页面失败', 'error');
                    pageController.showMainPage();
                }
            },

            // 显示我的页面
            showProfilePage: () => {
                elements.userName.textContent = appData.currentUser;
                profileController.renderAllEvents();
                profileController.updateProfileStats();

                elements.loginPage.classList.add('hidden');
                elements.mainPage.classList.add('hidden');
                elements.recordPage.classList.add('hidden');
                elements.statsPage.classList.add('hidden');
                elements.profilePage.classList.remove('hidden');
                elements.newEventModal.classList.add('hidden');
                elements.newEventModal.classList.remove('flex');
                elements.dayEventsModal.classList.add('hidden');
                elements.dayEventsModal.classList.remove('flex');
                elements.eventNoteModal.classList.add('hidden');
                elements.eventNoteModal.classList.remove('flex');
                
                // 显示底部导航栏
                elements.bottomNav.classList.remove('hidden');
                
                // 更新底部导航栏激活状态
                pageController.updateBottomNavActiveState('profile');
                // 重新绑定底部导航栏事件监听器
                pageController.bindBottomNavEvents();
            },

            // 显示新增事件弹窗
            showNewEventModal: () => {
                elements.newEventName.value = '';
                
                // 重置所有颜色按钮状态
                document.querySelectorAll('.event-color-btn').forEach(btn => {
                    btn.classList.remove('active', 'border-white');
                    btn.classList.add('border-transparent');
                });
                
                // 收起更多颜色面板
                const moreColorsContainer = document.getElementById('moreColorsContainer');
                const moreColorsBtn = document.getElementById('moreColorsBtn');
                moreColorsContainer.classList.add('hidden');
                moreColorsBtn.innerHTML = '<i class="fa fa-plus text-xs"></i>';
                
                // 获取当前用户已使用的颜色
                const userEvents = appData.fileSystem.events[appData.currentUser] || {};
                const usedColors = new Set();
                Object.values(userEvents).forEach(event => {
                    if (event.color) {
                        usedColors.add(event.color.toLowerCase());
                    }
                });
                
                // 查找第一个未使用的颜色（包括更多颜色中的）
                let firstUnusedColorBtn = null;
                const allColorBtns = document.querySelectorAll('.event-color-btn');
                for (let btn of allColorBtns) {
                    const color = btn.getAttribute('data-color').toLowerCase();
                    if (!usedColors.has(color)) {
                        firstUnusedColorBtn = btn;
                        break;
                    }
                }
                
                // 如果没有未使用的颜色，则使用第一个颜色
                if (!firstUnusedColorBtn) {
                    firstUnusedColorBtn = allColorBtns[0];
                }
                
                // 激活选中的颜色按钮
                if (firstUnusedColorBtn) {
                    firstUnusedColorBtn.classList.add('active', 'border-white');
                    firstUnusedColorBtn.classList.remove('border-transparent');
                }

                elements.newEventModal.classList.remove('hidden');
                elements.newEventModal.classList.add('flex');
                elements.newEventName.focus();
            },

            // 隐藏新增事件弹窗
            hideNewEventModal: () => {
                elements.newEventModal.classList.add('hidden');
                elements.newEventModal.classList.remove('flex');
            },

            // 显示日历事件详情弹窗
            showDayEventsModal: (date) => {
                const dateStr = utils.formatDate(date);
                const userRecords = appData.fileSystem.records[appData.currentUser] || {};
                const dayEvents = userRecords[dateStr] || [];

                appData.selectedDate = date;
                elements.dayEventsTitle.textContent = `${utils.formatDate(date, 'YYYY年MM月DD日')} 事件`;

                // 清空内容
                elements.dayEventsContent.innerHTML = '';

                if (dayEvents.length === 0) {
                    elements.dayEventsContent.innerHTML = `
                        <div class="text-center text-muted py-8">
                            <i class="fa fa-calendar-o text-4xl mb-2 opacity-30"></i>
                            <p>这一天没有记录事件</p>
                        </div>
                    `;
                } else {
                    const eventsList = document.createElement('div');
                    eventsList.className = 'space-y-3';

                    dayEvents.forEach((item, index) => {
                        const event = item.event;
                        const note = item.note;
                        const color = appData.fileSystem.events[appData.currentUser][event]?.color || '#8B5CF6';
                        const eventItem = document.createElement('div');
                        eventItem.className = 'p-3 bg-white/50 rounded-lg animate-fade-in cursor-pointer hover:bg-white transition-colors';
                        eventItem.style.animationDelay = `${index * 0.05}s`;
                        eventItem.innerHTML = `
                            <div class="flex items-start">
                                <div class="w-3 h-3 rounded-full mt-1.5 mr-3 flex-shrink-0" style="background-color: ${color}"></div>
                                <div class="flex-1">
                                    <div class="flex justify-between items-start">
                                        <span class="font-medium">${event}</span>
                                        <button class="text-muted hover:text-primary transition-colors edit-note-btn" data-event="${event}">
                                            <i class="fa fa-pencil"></i>
                                        </button>
                                    </div>
                                    ${note ? `
                                        <p class="text-sm text-muted mt-1 bg-gray-50 p-2 rounded text-xs">${note}</p>
                                    ` : ''}
                                </div>
                            </div>
                        `;
                        eventsList.appendChild(eventItem);
                    });

                    elements.dayEventsContent.appendChild(eventsList);

                    // 绑定备注编辑按钮事件
                    document.querySelectorAll('.edit-note-btn').forEach(btn => {
                        btn.addEventListener('click', (e) => {
                            e.stopPropagation();
                            const eventName = e.currentTarget.getAttribute('data-event');
                            pageController.showEventNoteModal(eventName);
                        });
                    });
                }

                elements.dayEventsModal.classList.remove('hidden');
                elements.dayEventsModal.classList.add('flex');
            },

            // 隐藏日历事件详情弹窗
            hideDayEventsModal: () => {
                elements.dayEventsModal.classList.add('hidden');
                elements.dayEventsModal.classList.remove('flex');
            },

            // 显示事件备注弹窗
            showEventNoteModal: (eventName) => {
                appData.editingEvent = eventName;
                elements.eventNoteTitle.textContent = `为"${eventName}"添加备注`;

                // 获取当前事件的备注
                const dateStr = utils.formatDate(appData.selectedDate);
                const userRecords = appData.fileSystem.records[appData.currentUser] || {};
                const dayEvents = userRecords[dateStr] || [];
                const eventItem = dayEvents.find(item => item.event === eventName);

                elements.eventNoteContent.value = eventItem?.note || '';

                elements.eventNoteModal.classList.remove('hidden');
                elements.eventNoteModal.classList.add('flex');
                elements.eventNoteContent.focus();
            },

            // 隐藏事件备注弹窗
            hideEventNoteModal: () => {
                elements.eventNoteModal.classList.add('hidden');
                elements.eventNoteModal.classList.remove('flex');
                appData.editingEvent = null;
            }
        };

        // 登录控制器
        const loginController = {
            init: () => {
                // 检查是否已有登录用户
                const savedUser = localStorage.getItem('slowDayCurrentUser');
                if (savedUser) {
                    appData.currentUser = savedUser;
                    loadUserDataFromServer().then(() => {
                        if (appData.fileSystem.users[savedUser]) {
                            pageController.showMainPage();
                        } else {
                            // 用户数据不存在，回到登录页面
                            appData.currentUser = null;
                            localStorage.removeItem('slowDayCurrentUser');
                            pageController.showLoginPage();
                        }
                    });
                } else {
                    pageController.showLoginPage();
                }

                
                elements.loginBtn.addEventListener('click', loginController.login);

                elements.loginPassword.addEventListener('keyup', (e) => {
                    if (e.key === 'Enter') {
                        loginController.login();
                    }
                });

                // 添加登录按钮动画效果
                elements.loginBtn.addEventListener('mousedown', () => {
                    elements.loginBtn.classList.add('scale-95');
                });

                elements.loginBtn.addEventListener('mouseup', () => {
                    elements.loginBtn.classList.remove('scale-95');
                });

                elements.loginBtn.addEventListener('mouseleave', () => {
                    elements.loginBtn.classList.remove('scale-95');
                });
            },

            login: async () => {
                try {
                    const password = elements.loginPassword.value.trim();

                    if (!password) {
                        utils.showToast('请输入登录口令', 'error');
                        return;
                    }

                    // 确保本地存储可用
                    if (typeof localStorage === 'undefined') {
                        utils.showToast('浏览器不支持本地存储，请更换浏览器', 'error');
                        return;
                    }

                    // 直接使用输入的口令作为用户名
                    const actualUsername = password;

                    // 临时设置当前用户以便加载数据
                    const previousUser = appData.currentUser;
                    appData.currentUser = actualUsername;

                    // 从服务器加载用户数据
                    await loadUserDataFromServer();

                    // 检查是否成功加载了用户数据
                    const userDataExists = appData.fileSystem.users[actualUsername] && 
                                          Object.keys(appData.fileSystem.users[actualUsername]).length > 0;

                    if (!userDataExists) {
                        // 如果用户不存在则创建新用户（文件系统风格）
                        appData.fileSystem.users[actualUsername] = {
                            createdAt: new Date().toISOString()
                        };

                        // 创建事件定义文件
                        appData.fileSystem.events[actualUsername] = {
                            '工作': { color: '#8B5CF6', count: 0 },
                            '休息': { color: '#EC4899', count: 0 },
                            '阅读': { color: '#F59E0B', count: 0 },
                            '运动': { color: '#10B981', count: 0 },
                            '学习': { color: '#3B82F6', count: 0 },
                            '购物': { color: '#6366F1', count: 0 },
                            '社交': { color: '#06B6D4', count: 0 },
                            '家务': { color: '#F43F5E', count: 0 }
                        };

                        // 创建记录数据文件
                        appData.fileSystem.records[actualUsername] = {};

                        // 保存用户数据到服务器
                        const saveResult = await saveUserDataToServer();
                        if (!saveResult) {
                            utils.showToast('保存用户数据失败', 'error');
                            appData.currentUser = previousUser; // 恢复之前的用户状态
                            return;
                        }
                    }

                    appData.currentUser = actualUsername;
                    localStorage.setItem('slowDayCurrentUser', actualUsername);

                    // 强制重绘登录按钮，确保动画显示
                    elements.loginBtn.classList.add('scale-95');
                    setTimeout(() => {
                        elements.loginBtn.classList.remove('scale-95');

                        // 延迟切换页面，确保动画完成
                        setTimeout(() => {
                            pageController.showMainPage();
                            utils.showToast('登录成功！');
                            // 清空密码输入框
                            elements.loginPassword.value = '';
                        }, 300);
                    }, 200);

                } catch (error) {
                    console.error('登录错误:', error);
                    utils.showToast('登录失败，请重试', 'error');
                }
            },

            logout: () => {
                appData.currentUser = null;
                localStorage.removeItem('slowDayCurrentUser');
                // 清空当前用户的数据
                appData.fileSystem = {
                    users: {},
                    events: {},
                    records: {}
                };
                pageController.showLoginPage();
                elements.loginPassword.value = '';
                utils.showToast('已退出登录');
            }
        };

        // 日历控制器
        const calendarController = {
            init: () => {
                // 绑定事件
                elements.prevMonth.addEventListener('click', () => {
                    appData.currentDate.setMonth(appData.currentDate.getMonth() - 1);
                    calendarController.renderCalendar();
                });

                elements.nextMonth.addEventListener('click', () => {
                    appData.currentDate.setMonth(appData.currentDate.getMonth() + 1);
                    calendarController.renderCalendar();
                });

                elements.addEventBtn.addEventListener('click', () => {
                    pageController.showRecordPage();
                });

                // 修复统计按钮点击事件
                elements.statsBtn.addEventListener('click', () => {
                    console.log('点击了统计按钮');
                    pageController.showStatsPage();
                });

                // 绑定日历事件详情弹窗事件
                elements.closeDayEventsModal.addEventListener('click', pageController.hideDayEventsModal);
                elements.gotoRecordBtn.addEventListener('click', () => {
                    pageController.hideDayEventsModal();
                    pageController.showRecordPage(appData.selectedDate);
                });

                // 点击弹窗背景关闭
                elements.dayEventsModal.addEventListener('click', (e) => {
                    if (e.target === elements.dayEventsModal) {
                        pageController.hideDayEventsModal();
                    }
                });

                // 事件备注弹窗事件
                elements.closeEventNoteModal.addEventListener('click', pageController.hideEventNoteModal);
                elements.cancelEventNoteBtn.addEventListener('click', pageController.hideEventNoteModal);
                elements.saveEventNoteBtn.addEventListener('click', calendarController.saveEventNote);

                // 点击弹窗背景关闭
                elements.eventNoteModal.addEventListener('click', (e) => {
                    if (e.target === elements.eventNoteModal) {
                        pageController.hideEventNoteModal();
                    }
                });

                // 备注输入框回车事件
                elements.eventNoteContent.addEventListener('keyup', (e) => {
                    if (e.key === 'Enter' && e.ctrlKey) {
                        calendarController.saveEventNote();
                    }
                });
            },

            // 保存事件备注
            saveEventNote: () => {
                if (!appData.editingEvent || !appData.selectedDate) return;

                const noteContent = elements.eventNoteContent.value.trim();
                const dateStr = utils.formatDate(appData.selectedDate);
                const eventName = appData.editingEvent;

                // 获取用户记录
                if (!appData.fileSystem.records[appData.currentUser]) {
                    appData.fileSystem.records[appData.currentUser] = {};
                }

                const userRecords = appData.fileSystem.records[appData.currentUser];

                // 获取日期记录
                if (!userRecords[dateStr]) return;

                const dayEvents = userRecords[dateStr];

                // 更新事件备注
                const eventIndex = dayEvents.findIndex(item => item.event === eventName);
                if (eventIndex !== -1) {
                    dayEvents[eventIndex].note = noteContent;

                    if (utils.saveFileSystem()) {
                        pageController.hideEventNoteModal();
                        pageController.showDayEventsModal(appData.selectedDate);
                        utils.showToast('备注保存成功');
                    } else {
                        utils.showToast('保存备注失败', 'error');
                    }
                }
            },

            // 渲染日历 (优化版本 - 减少DOM操作和重排重绘)
            renderCalendar: () => {
                const year = appData.currentDate.getFullYear();
                const month = appData.currentDate.getMonth();
                const today = new Date();
                const todayStr = utils.formatDate(today);

                // 更新月份标题
                elements.currentMonth.textContent = `${year}年${month + 1}月`;

                // 获取月份天数和第一天是星期几
                const daysInMonth = utils.getDaysInMonth(year, month);
                const firstDayOfMonth = utils.getFirstDayOfMonth(year, month);

                // 使用文档片段减少DOM重排
                const fragment = document.createDocumentFragment();

                // 添加空白格子
                for (let i = 0; i < firstDayOfMonth; i++) {
                    const emptyDay = document.createElement('div');
                    emptyDay.className = 'calendar-day p-1';
                    fragment.appendChild(emptyDay);
                }

                // 添加日期格子
                for (let day = 1; day <= daysInMonth; day++) {
                    const date = new Date(year, month, day);
                    const dateStr = utils.formatDate(date);
                    const userRecords = appData.fileSystem.records[appData.currentUser] || {};
                    const dayEvents = userRecords[dateStr] || [];

                    const dayElement = document.createElement('div');
                    dayElement.className = `calendar-day px-0 py-1 flex flex-col items-center justify-start rounded-xl border border-transparent hover:border-primary/30 hover:bg-primary/5 transition-all cursor-pointer relative group ${dateStr === todayStr ? 'bg-primary/5 border-primary/30' : ''
                        }`;

                    // 日期数字容器
                    const dayNumberContainer = document.createElement('div');
                    dayNumberContainer.className = 'w-full flex justify-center mb-1';

                    // 日期数字
                    const dayNumber = document.createElement('div');
                    dayNumber.className = `text-2xl font-medium w-8 h-8 flex items-center justify-center rounded-full ${dateStr === todayStr ? 'bg-primary text-white' : ''
                        }`;
                    dayNumber.textContent = day;
                    // 添加响应式字体大小
                    dayNumber.classList.add('text-responsive');
                    dayNumberContainer.appendChild(dayNumber);
                    dayElement.appendChild(dayNumberContainer);

                    // 事件标签容器
                    const eventsContainer = document.createElement('div');
                    eventsContainer.className = 'w-full px-1 flex flex-col items-center gap-1 overflow-hidden flex-1 max-h-[calc(100%-40px)]';

                    // 添加事件标签 - 最多显示3个事件
                    dayEvents.slice(0, 3).forEach((item, index) => {
                        const event = item.event;
                        const color = appData.fileSystem.events[appData.currentUser][event]?.color || '#8B5CF6';
                        const eventTag = document.createElement('span');
                        eventTag.className = 'text-xs py-1 rounded-full event-tag text-center w-full';
                        eventTag.style.backgroundColor = color;
                        eventTag.style.color = 'white';
                        eventTag.textContent = event;
                        eventTag.style.animationDelay = `${index * 0.05}s`;
                        eventTag.classList.add('animate-fade-in');
                        // 添加响应式字体大小
                        eventTag.classList.add('text-responsive-event');
                        eventsContainer.appendChild(eventTag);
                    });

                    // 如果有更多事件，显示省略号
                    if (dayEvents.length > 3) {
                        const moreTag = document.createElement('span');
                        moreTag.className = 'text-xs py-1 rounded-full event-tag text-center animate-fade-in w-full';
                        moreTag.style.backgroundColor = '#e5e7eb'; // bg-gray-200
                        moreTag.style.color = '#4b5563'; // text-gray-600
                        moreTag.style.animationDelay = '0.2s';
                        moreTag.textContent = `+${dayEvents.length - 3}`;
                        // 添加响应式字体大小
                        moreTag.classList.add('text-responsive-event');
                        eventsContainer.appendChild(moreTag);
                    }

                    dayElement.appendChild(eventsContainer);

                    // 添加点击事件
                    dayElement.addEventListener('click', () => {
                        pageController.showDayEventsModal(date);
                    });

                    fragment.appendChild(dayElement);
                }

                // 一次性更新DOM
                elements.calendarGrid.innerHTML = '';
                elements.calendarGrid.appendChild(fragment);
            },

            // 更新今日事件预览
            updateTodayEvents: () => {
                const today = utils.formatDate(new Date());
                const userRecords = appData.fileSystem.records[appData.currentUser] || {};
                const todayEvents = userRecords[today] || [];

                elements.todayEvents.innerHTML = '';

                if (todayEvents.length === 0) {
                    elements.todayEvents.innerHTML = '<div class="text-muted text-sm italic">今日暂无记录</div>';
                    return;
                }

                todayEvents.forEach((item, index) => {
                    const event = item.event;
                    const color = appData.fileSystem.events[appData.currentUser][event]?.color || '#8B5CF6';
                    const eventTag = document.createElement('div');
                    eventTag.className = 'px-3 py-1.5 text-xs rounded-lg text-white mr-2 mb-2 animate-fade-in card-hover shadow-sm hover:shadow-md transition-all duration-300 flex items-center justify-between max-w-[200px] group';
                    eventTag.style.backgroundColor = color;
                    eventTag.style.animationDelay = `${index * 0.05}s`;
                    eventTag.innerHTML = `
                        <span>${event}</span>
                        ${item.note ? '<i class="fa fa-sticky-note-o text-white/70 group-hover:text-white ml-1"></i>' : ''}
                    `;

                    // 添加点击事件，打开详情弹窗
                    eventTag.addEventListener('click', (e) => {
                        e.stopPropagation();
                        const today = new Date();
                        pageController.showDayEventsModal(today);
                    });

                    elements.todayEvents.appendChild(eventTag);
                });
            }
        };

        // 记录控制器
        const recordController = {
            init: () => {
                // 绑定事件
                elements.backToCalendar.addEventListener('click', pageController.showMainPage);
                elements.addNewEventBtn.addEventListener('click', pageController.showNewEventModal);
                elements.closeNewEventModal.addEventListener('click', pageController.hideNewEventModal);
                elements.confirmNewEventBtn.addEventListener('click', recordController.addNewEvent);
                elements.saveRecordBtn.addEventListener('click', recordController.saveRecord);

                // 颜色选择按钮 (使用事件委托优化性能)
                document.querySelector('#newEventModal').addEventListener('click', (e) => {
                    // 处理颜色按钮点击
                    if (e.target.classList.contains('event-color-btn')) {
                        document.querySelectorAll('.event-color-btn').forEach(b => {
                            b.classList.remove('active', 'border-white');
                            b.classList.add('border-transparent');
                        });
                        e.target.classList.add('active', 'border-white');
                        e.target.classList.remove('border-transparent');
                    }
                    
                    // 处理更多颜色按钮点击
                    if (e.target.closest('#moreColorsBtn')) {
                        const moreColorsContainer = document.getElementById('moreColorsContainer');
                        const moreColorsBtn = document.getElementById('moreColorsBtn');
                        if (moreColorsContainer.classList.contains('hidden')) {
                            moreColorsContainer.classList.remove('hidden');
                            moreColorsBtn.innerHTML = '<i class="fa fa-minus text-xs"></i>';
                        } else {
                            moreColorsContainer.classList.add('hidden');
                            moreColorsBtn.innerHTML = '<i class="fa fa-plus text-xs"></i>';
                        }
                    }
                });

                // 新增事件输入框回车事件
                elements.newEventName.addEventListener('keyup', (e) => {
                    if (e.key === 'Enter') {
                        recordController.addNewEvent();
                    }
                });

                // 点击弹窗背景关闭
                elements.newEventModal.addEventListener('click', (e) => {
                    if (e.target === elements.newEventModal) {
                        pageController.hideNewEventModal();
                    }
                });
                
                // 使用事件委托处理常用事件的点击和删除操作
                elements.commonEvents.addEventListener('click', (e) => {
                    const eventButton = e.target.closest('button[data-event]');
                    const deleteButton = e.target.closest('.delete-event-btn');
                    
                    if (eventButton && !deleteButton) {
                        // 添加事件点击
                        const event = eventButton.getAttribute('data-event');
                        // 避免重复添加
                        if (!appData.selectedEvents.includes(event)) {
                            appData.selectedEvents.push(event);
                            recordController.renderSelectedEvents();
                        }
                    } else if (deleteButton) {
                        // 删除事件按钮点击
                        e.stopPropagation();
                        const event = deleteButton.getAttribute('data-event');
                        if (confirm(`确定要删除事件"${event}"吗？`)) {
                            delete appData.fileSystem.events[appData.currentUser][event];
                            
                            // 从已选择事件中移除
                            const selectedIndex = appData.selectedEvents.indexOf(event);
                            if (selectedIndex > -1) {
                                appData.selectedEvents.splice(selectedIndex, 1);
                                recordController.renderSelectedEvents();
                            }
                            
                            if (utils.saveFileSystem()) {
                                recordController.renderCommonEvents();
                                utils.showToast('事件删除成功');
                            } else {
                                utils.showToast('删除事件失败', 'error');
                            }
                        }
                    }
                });
            },

            // 渲染已选择的事件
            renderSelectedEvents: () => {
                elements.selectedEvents.innerHTML = '';

                if (appData.selectedEvents.length === 0) {
                    elements.selectedEvents.innerHTML = '<div class="text-muted text-sm italic">未选择任何事件</div>';
                    return;
                }

                appData.selectedEvents.forEach((event, index) => {
                    const color = appData.fileSystem.events[appData.currentUser][event]?.color || '#8B5CF6';
                    const eventTag = document.createElement('div');
                    eventTag.className = 'px-3 py-1.5 text-xs rounded-lg text-white flex items-center justify-between max-w-[140px] animate-fade-in card-hover shadow-sm hover:shadow-md transition-all duration-300';
                    eventTag.style.backgroundColor = color;
                    eventTag.style.animationDelay = `${index * 0.05}s`;
                    eventTag.innerHTML = `
                        <span>${event}</span>
                        <button class="ml-2 text-white/80 hover:text-white" data-index="${index}">
                            <i class="fa fa-times-circle"></i>
                        </button>
                    `;

                    eventTag.querySelector('button').addEventListener('click', (e) => {
                        const idx = parseInt(e.currentTarget.getAttribute('data-index'));
                        appData.selectedEvents.splice(idx, 1);
                        recordController.renderSelectedEvents();
                    });

                    elements.selectedEvents.appendChild(eventTag);
                });
            },

            // 渲染常用事件 (优化版本 - 减少DOM操作和事件监听器)
            renderCommonEvents: () => {
                elements.commonEvents.innerHTML = '';

                // 获取用户事件并按使用次数排序
                const userEvents = appData.fileSystem.events[appData.currentUser] || {};
                const sortedEvents = Object.keys(userEvents)
                    .sort((a, b) => (userEvents[b].count || 0) - (userEvents[a].count || 0));

                // 只显示前24个事件
                const displayEvents = sortedEvents.slice(0, 24);

                if (displayEvents.length === 0) {
                    elements.commonEvents.innerHTML = '<div class="col-span-3 text-center text-muted py-4">暂无事件，请添加新事件</div>';
                    return;
                }

                // 使用文档片段减少DOM重排
                const fragment = document.createDocumentFragment();

                displayEvents.forEach((event, index) => {
                    const eventData = userEvents[event];
                    const eventContainer = document.createElement('div');
                    eventContainer.className = 'relative py-3 border border-gray-200 rounded-xl hover:border-primary hover:bg-primary/5 transition-colors flex flex-col items-center justify-center card-hover animate-fade-in';
                    eventContainer.style.animationDelay = `${index * 0.03}s`;
                    eventContainer.innerHTML = `
                        <button class="w-full h-full flex flex-col items-center justify-center" data-event="${event}">
                            <div class="w-3 h-3 rounded-full mb-2" style="background-color: ${eventData.color}"></div>
                            <span class="text-sm">${event}</span>
                            ${eventData.count > 0 ? `<span class="text-xs text-muted mt-1">${eventData.count}次</span>` : ''}
                        </button>
                        <button class="absolute top-1 right-1 text-muted hover:text-danger delete-event-btn" data-event="${event}">
                            <i class="fa fa-trash-o text-xs"></i>
                        </button>
                    `;
                    
                    fragment.appendChild(eventContainer);
                });
                
                // 一次性更新DOM
                elements.commonEvents.appendChild(fragment);
            },

            // 添加新事件
            addNewEvent: () => {
                const eventName = elements.newEventName.value.trim();

                if (!eventName) {
                    utils.showToast('请输入事件名称', 'error');
                    return;
                }

                // 检查事件是否已存在
                if (appData.fileSystem.events[appData.currentUser] && appData.fileSystem.events[appData.currentUser][eventName]) {
                    utils.showToast('事件已存在', 'error');
                    return;
                }

                // 获取选中的颜色
                const selectedColor = document.querySelector('.event-color-btn.active').getAttribute('data-color');

                // 添加新事件（文件系统风格）
                if (!appData.fileSystem.events[appData.currentUser]) {
                    appData.fileSystem.events[appData.currentUser] = {};
                }

                appData.fileSystem.events[appData.currentUser][eventName] = {
                    color: selectedColor,
                    count: 0
                };

                // 自动选择新添加的事件
                appData.selectedEvents.push(eventName);

                if (utils.saveFileSystem()) {
                    pageController.hideNewEventModal();
                    recordController.renderCommonEvents();
                    recordController.renderSelectedEvents();
                    utils.showToast('事件添加成功');
                } else {
                    utils.showToast('保存事件失败', 'error');
                }

                // 清空输入框
                elements.newEventName.value = '';
            },

            // 保存记录
            saveRecord: () => {
                const dateStr = utils.formatDate(appData.selectedDate);

                // 获取用户记录（文件系统风格）
                if (!appData.fileSystem.records[appData.currentUser]) {
                    appData.fileSystem.records[appData.currentUser] = {};
                }

                const userRecords = appData.fileSystem.records[appData.currentUser];

                // 获取旧记录用于比较
                const oldEvents = userRecords[dateStr] ? userRecords[dateStr].map(item => item.event) : [];
                
                // 转换为带结构的记录格式，支持备注
                const structuredEvents = appData.selectedEvents.map(event => ({
                    event: event,
                    note: '' // 初始备注为空
                }));

                // 检查是否有旧记录，保留备注信息
                if (userRecords[dateStr]) {
                    structuredEvents.forEach(newEvent => {
                        const oldEvent = userRecords[dateStr].find(e => e.event === newEvent.event);
                        if (oldEvent && oldEvent.note) {
                            newEvent.note = oldEvent.note;
                        }
                    });
                }

                // 更新记录
                userRecords[dateStr] = structuredEvents;

                // 更新事件计数 - 只对新增的事件增加计数，对删除的事件减少计数
                // 先找出新增的事件（在新记录中但不在旧记录中）
                const newEvents = appData.selectedEvents.filter(event => !oldEvents.includes(event));
                
                // 再找出删除的事件（在旧记录中但不在新记录中）
                const deletedEvents = oldEvents.filter(event => !appData.selectedEvents.includes(event));
                
                // 对新增的事件增加计数
                newEvents.forEach(event => {
                    if (appData.fileSystem.events[appData.currentUser] && appData.fileSystem.events[appData.currentUser][event]) {
                        appData.fileSystem.events[appData.currentUser][event].count =
                            (appData.fileSystem.events[appData.currentUser][event].count || 0) + 1;
                    }
                });
                
                // 对删除的事件减少计数
                deletedEvents.forEach(event => {
                    if (appData.fileSystem.events[appData.currentUser] && appData.fileSystem.events[appData.currentUser][event]) {
                        appData.fileSystem.events[appData.currentUser][event].count =
                            Math.max(0, (appData.fileSystem.events[appData.currentUser][event].count || 0) - 1);
                    }
                });

                if (utils.saveFileSystem()) {
                    pageController.showMainPage();
                    utils.showToast('记录保存成功');
                } else {
                    utils.showToast('保存记录失败', 'error');
                }
            }
        };

        // 统计控制器
        const statsController = {
            init: () => {
                elements.backToMainFromStats.addEventListener('click', pageController.showMainPage);
            },

            renderStats: () => {
                try {
                    const userRecords = appData.fileSystem.records[appData.currentUser] || {};
                    const userEvents = appData.fileSystem.events[appData.currentUser] || {};

                    // 获取最近30天的记录
                    const recentDates = [];
                    const today = new Date();

                    for (let i = 29; i >= 0; i--) {
                        const date = new Date(today);
                        date.setDate(today.getDate() - i);
                        recentDates.push(utils.formatDate(date));
                    }

                    // 计算统计数据
                    const totalDays = Object.keys(userRecords).length;
                    let totalEvents = 0;
                    const eventCount = {};

                    Object.values(userRecords).forEach(events => {
                        totalEvents += events.length;
                        events.forEach(item => {
                            const event = item.event;
                            eventCount[event] = (eventCount[event] || 0) + 1;
                        });
                    });

                    const mostFrequentEvent = Object.entries(eventCount).sort((a, b) => b[1] - a[1])[0]?.[0] || '无';

                    // 更新统计文本
                    elements.totalDays.textContent = `${totalDays}天`;
                    elements.totalEvents.textContent = `${totalEvents}件`;
                    elements.mostFrequentEvent.textContent = mostFrequentEvent;

                    // 月度事件数量图表
                    const monthlyData = [];
                    const monthlyLabels = [];

                    // 获取当前月份数据
                    const currentMonth = today.getMonth();
                    const currentYear = today.getFullYear();
                    const daysInMonth = utils.getDaysInMonth(currentYear, currentMonth);

                    for (let day = 1; day <= daysInMonth; day++) {
                        const date = new Date(currentYear, currentMonth, day);
                        const dateStr = utils.formatDate(date);
                        const events = userRecords[dateStr] || [];

                        if (day % 3 === 0 || day === daysInMonth) {
                            monthlyLabels.push(day + '日');
                            monthlyData.push(events.length);
                        }
                    }

                    // 销毁已存在的图表
                    if (window.monthlyChart && typeof window.monthlyChart.destroy === 'function') {
                        window.monthlyChart.destroy();
                    }

                    // 创建月度图表
                    const monthlyCtx = document.getElementById('monthlyChart').getContext('2d');
                    window.monthlyChart = new Chart(monthlyCtx, {
                        type: 'line',
                        data: {
                            labels: monthlyLabels,
                            datasets: [{
                                label: '每日事件数',
                                data: monthlyData,
                                borderColor: '#6366F1',
                                backgroundColor: 'rgba(99, 102, 241, 0.1)',
                                tension: 0.4,
                                fill: true,
                                pointBackgroundColor: '#6366F1',
                                pointRadius: 4,
                                pointHoverRadius: 6
                            }]
                        },
                        options: {
                            responsive: true,
                            maintainAspectRatio: false,
                            plugins: {
                                legend: {
                                    display: false
                                },
                                tooltip: {
                                    backgroundColor: 'rgba(255, 255, 255, 0.95)',
                                    titleColor: '#333',
                                    bodyColor: '#666',
                                    borderColor: '#eee',
                                    borderWidth: 1,
                                    padding: 10,
                                    boxPadding: 5,
                                    usePointStyle: true,
                                    callbacks: {
                                        label: function (context) {
                                            return `事件数: ${context.raw}`;
                                        }
                                    }
                                }
                            },
                            scales: {
                                y: {
                                    beginAtZero: true,
                                    ticks: {
                                        precision: 0
                                    },
                                    grid: {
                                        color: 'rgba(0, 0, 0, 0.05)'
                                    }
                                },
                                x: {
                                    grid: {
                                        display: false
                                    }
                                }
                            }
                        }
                    });

                    // 事件分布图表
                    const eventLabels = [];
                    const eventData = [];
                    const eventColors = [];

                    Object.entries(userEvents)
                        .sort((a, b) => (b[1].count || 0) - (a[1].count || 0))
                        .slice(0, 5)
                        .forEach(([name, data]) => {
                            eventLabels.push(name);
                            eventData.push(data.count || 0);
                            eventColors.push(data.color);
                        });

                    // 销毁已存在的图表
                    if (window.eventsChart && typeof window.eventsChart.destroy === 'function') {
                        window.eventsChart.destroy();
                    }

                    // 创建事件分布图表
                    const eventsCtx = document.getElementById('eventsChart').getContext('2d');
                    window.eventsChart = new Chart(eventsCtx, {
                        type: 'doughnut',
                        data: {
                            labels: eventLabels,
                            datasets: [{
                                data: eventData,
                                backgroundColor: eventColors,
                                borderWidth: 0,
                                hoverOffset: 10
                            }]
                        },
                        options: {
                            responsive: true,
                            maintainAspectRatio: false,
                            plugins: {
                                legend: {
                                    position: 'bottom',
                                    labels: {
                                        usePointStyle: true,
                                        padding: 15
                                    }
                                },
                                tooltip: {
                                    backgroundColor: 'rgba(255, 255, 255, 0.95)',
                                    titleColor: '#333',
                                    bodyColor: '#666',
                                    borderColor: '#eee',
                                    borderWidth: 1,
                                    padding: 10,
                                    boxPadding: 5,
                                    usePointStyle: true,
                                    callbacks: {
                                        label: function (context) {
                                            return `次数: ${context.raw}`;
                                        }
                                    }
                                }
                            },
                            cutout: '65%'
                        }
                    });
                } catch (error) {
                    console.error('渲染统计图表失败:', error);
                    utils.showToast('加载统计数据失败', 'error');
                }
            }
        };

        // 个人资料控制器
        const profileController = {
            init: () => {
                elements.backToMainFromProfile.addEventListener('click', pageController.showMainPage);
                elements.logoutBtn.addEventListener('click', loginController.logout);
            },

            renderAllEvents: () => {
                elements.allEventsList.innerHTML = '';

                const userEvents = appData.fileSystem.events[appData.currentUser] || {};

                if (Object.keys(userEvents).length === 0) {
                    elements.allEventsList.innerHTML = '<div class="text-center text-muted py-4">暂无事件</div>';
                    return;
                }

                const sortedEvents = Object.entries(userEvents).sort((a, b) => (b[1].count || 0) - (a[1].count || 0));

                sortedEvents.forEach(([name, data], index) => {
                    const eventItem = document.createElement('div');
                    eventItem.className = 'flex justify-between items-center p-3 hover:bg-gray-50 rounded-lg transition-colors card-hover animate-fade-in';
                    eventItem.style.animationDelay = `${index * 0.03}s`;
                    eventItem.innerHTML = `
                        <div class="flex items-center">
                            <div class="w-3 h-3 rounded-full mr-3" style="background-color: ${data.color}"></div>
                            <span>${name}</span>
                        </div>
                        <span class="text-sm font-medium">${data.count || 0}次</span>
                    `;
                    elements.allEventsList.appendChild(eventItem);
                });

                // 更新个人资料统计数据
                elements.profileEventTypes.textContent = sortedEvents.length;
            },

            updateProfileStats: () => {
                const userRecords = appData.fileSystem.records[appData.currentUser] || {};
                const userEvents = appData.fileSystem.events[appData.currentUser] || {};

                // 计算统计数据
                const totalDays = Object.keys(userRecords).length;
                let totalEvents = 0;

                Object.values(userRecords).forEach(events => {
                    totalEvents += events.length;
                });

                // 更新统计数据
                elements.profileTotalDays.textContent = totalDays;
                elements.profileTotalEvents.textContent = totalEvents;
                elements.profileEventTypes.textContent = Object.keys(userEvents).length;
            }
        };

        // 初始化应用
        const initApp = () => {
            // 初始化所有控制器
            loginController.init();
            calendarController.init();
            recordController.init();
            statsController.init();
            profileController.init();

            // 设置今日日期
            elements.todayDate.textContent = utils.formatDate(new Date(), 'YYYY年MM月DD日');
            
            // 初始化底部导航栏事件监听器
            pageController.bindBottomNavEvents();
        };

        // 启动应用
        document.addEventListener('DOMContentLoaded', initApp);
    </script>
</body>

</html>